package com.livegoods.dao.impl;

import com.livegoods.commons.pojo.LivegoodsResult;
import com.livegoods.dao.HouseDao4Redis;
import com.livegoods.pojo.House;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.stereotype.Repository;

@Repository
public class HouseDao4RedisImpl implements HouseDao4Redis {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public House get(String key) {
        return (House)redisTemplate.opsForValue().get(key);
    }

    @Override
    public boolean set(String key,final Object value) {
        //1，修改Redis中房屋租赁状态 isRent=false （已出租）
        try {
           //设置Redis的事务支持状态，当前代码后面的操作原子性
            redisTemplate.setEnableTransactionSupport(true);

            Object result = redisTemplate.execute(new SessionCallback() {
                @Override
                public Object execute(RedisOperations redisOperations) throws DataAccessException {

                    //通过key获取数据
                    House house = (House) redisOperations.opsForValue().get(key);

                    //如果出租状态为false，说明已经出租了，直接返回空，不做任何操作
                    if(!house.getIsRent()){
                        return  null;
                    }
                    //设置redisTemplate操作为原子性操作，单线程
                    redisTemplate.multi();

                    //讲修改后的数据存储到Redis
                    redisOperations.opsForValue().set(key,value);

                    return redisOperations.exec();
                }
            });
            //关闭支持事务状态
            redisTemplate.setEnableTransactionSupport(false);

            System.out.println("redisOperations.exec()执行结果 = " + result);
            //房屋已经被预定，返回 false
            if (result == null){
                return false;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return true;
    }
}
